﻿@page "/producttype"
@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject ProductCategoryService ProductCategoryService
@inject ContextMenuService ContextMenuService

<RadzenText TextStyle="TextStyle.H4">商品分类管理</RadzenText>
<PageTitle>商品分类管理</PageTitle>
<RadzenCard class="content" Style="display:flex;">
    <RadzenStack Orientation="Orientation.Horizontal" Style="flex:1; height:85vh;">
        <RadzenTree Style="width: 20%; margin: 10px 0px 10px 10px;" @bind-Value=@SelectedNode Data=@Tree ItemContextMenu="ItemContextMenu" Change=OnTreeChange>
            <RadzenTreeLevel TextProperty="Name"
                             ChildrenProperty="Children"
                             Expanded=@ShouldExpand
                             HasChildren=@(e => (e as TreeProductTypeDto)!.Children.Any()) />
        </RadzenTree>
        <RadzenCard Style="display:flex; flex-direction:column; width: 80%; height:83vh; margin:10px 10px 0px 0px;">
            <RadzenStack Orientation="Orientation.Horizontal" Style="display:flex; flex-direction:column">
                <RadzenTextBox @bind-Value="condition" Placeholder="分类" Style="margin:10px 0px" />
                <RadzenButton Text="查询" Icon="refresh" Click=@(args => Search()) ButtonStyle="ButtonStyle.Primary" 
                Style="margin:10px 5px"/>
                <RadzenButton Text="新增" Icon="add_circle" Click=@(args => Add((SelectedNode as TreeProductTypeDto)!)) ButtonStyle="ButtonStyle.Primary" Style="margin:10px 5px 10px 0px"/>
            </RadzenStack>
            <RadzenDataGrid Style="flex:1;height:80vh;" TItem="ProductCategory" EmptyText="暂无数据" Data="@productCategories" GridLines="Radzen.DataGridGridLines.Default" AllowPaging="true" AllowSorting="true">
                <Columns>
                    <RadzenDataGridColumn TItem="ProductCategory" Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                    <RadzenDataGridColumn TItem="ProductCategory" Property="Name" Title="名称" />
                </Columns>
            </RadzenDataGrid>
        </RadzenCard>
    </RadzenStack>
</RadzenCard>

@code {
    ObservableCollection<ProductCategory>? productCategories;
    List<TreeProductTypeDto>? Tree { get; set; }
    object? SelectedNode;
    private string? condition = "";
    bool ShouldExpand(object data)
    {
        return true;
    }
    void ItemContextMenu(TreeItemContextMenuEventArgs args)
    {
        ContextMenuService.Open(args,
            new List<ContextMenuItem> {
                new ContextMenuItem(){ Text = "新增", Value = 1, Icon = "add_circle" },
                new ContextMenuItem(){ Text = "修改", Value = 2, Icon = "edit" },
                new ContextMenuItem(){ Text = "删除", Value = 3, Icon = "delete" },
                            },
            (e) =>
            {
                if ((int)e.Value == 1)
                {
                    Add((TreeProductTypeDto)args.Value);
                }
                else if ((int)e.Value == 2)
                {
                    Update((TreeProductTypeDto)args.Value);
                }
                else if ((int)e.Value == 3)
                {
                    Delete((TreeProductTypeDto)args.Value);
                }
            });
    }

    private void OnTreeChange(object value)
    {
        var x = value as Radzen.TreeEventArgs;
        var node = (TreeProductTypeDto)x!.Value;
        SelectedNode = node;
        var list = ProductCategoryService.SearchProductType(new BaseInput());
        var children = list.Where(s=>s.ParentId == node.Id);
        productCategories = new ObservableCollection<ProductCategory>(children);
    }

    private void Search()
    {
        BaseInput input = new BaseInput()
            {
                keyword = condition!,
            };
        var list = ProductCategoryService.SearchProductType(input);
        productCategories = new ObservableCollection<ProductCategory>(list!);
    }

    private async void Add(TreeProductTypeDto parent)
    {
        if (parent == null)
        {
            await DialogService.Alert("未选择父节点", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        }

        var productType = new ProductCategory();
        ProductCategory result = await DialogService.OpenAsync<ProductTypeAddDialog>($"新增商品分类",
               new Dictionary<string, object>() {
                   { "PProductType", productType },
                   { "PParent", parent! }
                   },
               new DialogOptions()
                   {
                       Resizable = true,
                       Draggable = true,
                       Resize = OnResize,
                       Drag = OnDrag,
                       Width = "700px",
                       Height = "382px",
                       Left = null,
                       Top = null
                   });

        if (result != null)
        {
            Tree = ProductCategoryService.GetTree();
            StateHasChanged();
        }
    }

    private async void Update(TreeProductTypeDto selectedItem)
    {
        if (selectedItem.ParentId == 0)
        {
            await DialogService.Alert("根节点不允许修改", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        };

        var productType = ProductCategoryService.Get(selectedItem.Id);
        var node = SelectedNode as TreeProductTypeDto;
        var parent = new TreeProductTypeDto()
            {
                Id = node!.Id,
                Name = node.Name,
                ParentId = node.ParentId,
                Sort = node.Sort
            };

        var result = await DialogService.OpenAsync<ProductTypeAddDialog>($"修改商品分类",
                  new Dictionary<string, object>() {
                          { "PProductType", productType! },
                          { "PParent", parent}
                      },
                  new DialogOptions()
                      {
                          Resizable = true,
                          Draggable = true,
                          Resize = OnResize,
                          Drag = OnDrag,
                          Width = "700px",
                          Height = "382px",
                          Left = null,
                          Top = null
                      });
        if (result != null)
        {
            Tree = ProductCategoryService.GetTree();
            StateHasChanged();
        }
    }

    private async void Delete(TreeProductTypeDto selectedItem)
    {
        if (selectedItem.ParentId == 0)
        {
            await DialogService.Alert("根节点不允许删除", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        };

        var productType = ProductCategoryService.Get(selectedItem.Id);
        var dialogResult = await DialogService.Confirm("确定要删除选择的商品分类吗？", "删除", new ConfirmOptions()
            {
                OkButtonText = "确定",
                CancelButtonText = "取消"
            });

        if ((bool)dialogResult)
        {
            try
            {
                ProductCategoryService.Delete(productType!.Id);
                await DialogService.Alert("删除成功。", "提示信息", new AlertOptions() { OkButtonText = "确定" });
                Tree!.Remove(selectedItem);
                productCategories?.Remove(productType);
            }
            catch (Exception ex)
            {
                await DialogService.Alert(ex.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
                return;
            }
        }
    }

    void OnDrag(System.Drawing.Point point)
    {
    }

    void OnResize(System.Drawing.Size size)
    {
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        Tree = ProductCategoryService.GetTree();
        SelectedNode = Tree?.FirstOrDefault();
    }
}

